<?php
/**
 * FileController.class.php
 * 
 * @author shenglu.li
 * @copyright www.cnblog.com/lsl8966
 * @package Controller
 * @version $Id: FileController.class.php 1.0 2017-5-31 17:18:13Z $
 *
 */

class FileController extends Service{
    private $current_dt;
    private $attach_name;
    private static $p_attachpath = '/apps/dat/web/working/file.51guipiao.com/upload/';//帖子附件路径
    private static $attachrootpath = array(
        //帖子类型对应文件夹名
        "0"=>"menu/",//默认路径
        "1"=>"advert/",//广告路径
    );
    private static $attachtypepath = array(
        //帖子类型对应文件夹名
        "0"=>"images/",//图片路径
        "1"=>"voice/",//语音路径
        "2"=>"video/",//视频路径
        "3"=>"doc/",//
        "4"=>"docx/",//
        "5"=>"xls/",//
        "6"=>"zip/",//
        "7"=>"rar/",//
        "8"=>"xlsx/",//
        "9"=>"png/",//
        "10"=>"gif/",//
    );
    private static $attachext = array(
        //帖子类型对应后缀名
        "0"=>".jpg",//图片格式
        "1"=>".amr",//语音格式
        "2"=>".avi",//视频格式
        "3"=>".doc",//视频格式
        "4"=>".docx",//
        "5"=>".xls",//
        "6"=>".zip",//
        "7"=>".rar",//
        "8"=>".xlsx",//
        "9"=>".png",//
        "10"=>".gif",//
    );

    private $result;

    /**
     * 前函数
     */
     protected function init(){
         parent::init();
         $this->current_dt = $this->_getTimestamp();
         $this->jsonObj->attach_kind = $this->jsonObj->attach_kind?$this->jsonObj->attach_kind:0;
         if($this->jsonObj->api_key){
             self::$p_attachpath = self::$p_attachpath.$this->jsonObj->api_key.SEP;
         }
     }

    function __destruct(){
    }

    /**
     * 生成默认图片
     */
    public function defaultAction(){
        /* Set width and height in proportion of genuine PHP logo */
        $text = $this->jsonObj->text?$this->jsonObj->text:'DTMaster';
        $fill_color = $this->jsonObj->fill_color?$this->jsonObj->fill_color:'0b3f89';
        $font_color = $this->jsonObj->font_color?$this->jsonObj->font_color:'ffffff';
        $font_fill_color = $this->jsonObj->font_fill_color?$this->jsonObj->font_fill_color:'000000';
        $font_size = $this->jsonObj->font_size?$this->jsonObj->font_size:50;
        $width = $this->jsonObj->width?$this->jsonObj->width:400;
        $height = $this->jsonObj->height?$this->jsonObj->height:210;
        /* Create an Imagick object with transparent canvas */
        $img = new Imagick();
        $img->newImage($width, $height, new ImagickPixel('transparent'));

        /* New ImagickDraw instance for ellipse draw */
        $draw = new ImagickDraw();
        /* Set purple fill color for ellipse */
        $draw->setFillColor('#'.$fill_color);
        /* Set ellipse dimensions */
        $draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
        /* Draw ellipse onto the canvas */
        $img->drawImage($draw);

        /* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
        $draw->setFillColor('#'.$font_fill_color);
        /* Set stroke border to white color */
        $draw->setStrokeColor('#'.$font_color);
        /* Set stroke border thickness */
        $draw->setStrokeWidth(2);
        /* Set font kerning (negative value means that letters are closer to each other) */
        $draw->setTextKerning(-2);
        /* Set font and font size used in PHP logo */
        $draw->setFont('./skin/assets/font/STSONG.TTF');
        $draw->setFontSize($font_size);
        /* Center text horizontally and vertically */
        $draw->setGravity(Imagick::GRAVITY_CENTER);
        /* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
        $img->annotateImage($draw, 0, -10, 0, $text);
        $img->setImageFormat('png');
        /* Set appropriate header for PNG and output the image */
        header('Content-Type: image/png');
        echo $img;
        exit;
    }

    /**
     * 上传文件
     */
    public function uploadAction(){
        $stream = file_get_contents('php://input');
        if(!$stream){
            $stream = $this->jsonObj->content;
        }
        if(is_numeric($this->jsonObj->file_length) && strlen($stream) != $this->jsonObj->file_length){
            $this->result = '-4';
        }else{
            //获得存储路径
            $path = self::$p_attachpath.self::$attachrootpath[$this->jsonObj->attach_kind].$this->_getTimestampToDateTime($this->current_dt)
                .SEP.self::$attachtypepath[$this->jsonObj->file_type];
            if($this->jsonObj->attach_name){
                $this->attach_name = $this->attach_name.self::$attachext[$this->jsonObj->file_type];
            }else{
                $this->attach_name = $this->current_dt.self::$attachext[$this->jsonObj->file_type];
            }
            if(file::writeFile($path.$this->attach_name,$stream)){
                $this->result = 0;
                //保存成功,准备压缩
                if(file_exists($path.$this->attach_name)){
                    if($this->jsonObj->file_type == 0){
                        //TODO 裁剪
                        $image = new Imagick($path.$this->attach_name);
                        $image->thumbnailImage(200, 100);
                        $image->writeImage(str_replace(".jpg","_s.jpg",$path.$this->attach_name));
                        $image->destroy();
                        //同步压缩
                        exec("/usr/local/bin/jpegoptim  --strip-all --all-progressive -o -f --max=80 $path$this->attach_name");
                    }
                }
            }
        }
        $this->ajax(200,'ok',array('result'=>$this->result,'attach_name'=>$this->attach_name));
    }

    /**
     * 下载文件
     * 文件名称_s_宽x高.jpg
     */
    public function downloadAction(){
        $fullfilename = $this->_getFullName($this->jsonObj->attach_name,$type);
        if(!file_exists($fullfilename)){
            $fullfilename = str_replace($this->jsonObj->api_key.SEP,"",$fullfilename);
        }
        $source_image = preg_replace("/_s(.*).jpg/",".jpg",$fullfilename);
        if(file_exists($source_image)){
            if($type == 0 ){
                header('Content-type: image/jpeg');
            }
            header("attach_name: " . $this->jsonObj->attach_name);
            header("fullname: " . $fullfilename);
            header("file_type: " .$type);
            header("task_id: " .$this->jsonObj->task_id);
            //同步压缩
            exec("/usr/local/bin/jpegoptim  --strip-all --all-progressive -o -f --max=80 $source_image");
            if(strstr($this->jsonObj->attach_name,'_s')){
                //判断缩略图是否存在
                if(file_exists($fullfilename)){
                    http::download($fullfilename);
                }else{
                    $str = substr($fullfilename,strpos($fullfilename,'_s')+3,-4);
                    $arr = explode("x",$str);
                    $width = 150;
                    $height = 0;
                    if(count($arr)>1){
                        $width = $arr[0];
                        $height = $arr[1];
                    }
                    //取得原图
                    $image = new Imagick($source_image);
                    $image->thumbnailImage($width, $height);
                    $image->writeImage($fullfilename);
                    $image->destroy();
                }
            }
            http::download($fullfilename);
        }
    }

    private function _getTimestamp(){
        return time().substr(microtime(), 2,6);
    }

    private function _getTimestampToDateTime($timestamp){
        $timestamp = substr($timestamp, 0,  10);
        return date("Ymd", $timestamp);
    }

    /**
     * 获取完整路径
     */
    function _getFullName($file_name,&$type){
        $ext = array_pop(explode('.', $file_name));
        $ext_len = strlen($ext)+1;
        $ext = strtolower(substr($file_name, strlen($file_name) - $ext_len, $ext_len));
        for($i=0;$i<count(self::$attachext);$i++){
            if($ext == self::$attachext[$i]){
                $type_dir = self::$attachtypepath[$i];
                $type = $i;
                break;
            }
        }
        if(!$type_dir)return NULL;
        $commit_dt = substr($file_name,0,-$ext_len);
        $fullfilename = self::$p_attachpath.self::$attachrootpath[$this->jsonObj->attach_kind]
            .$this->_getTimestampToDateTime($commit_dt).'/'.$type_dir.$file_name;
        if(file_exists($fullfilename)){
            return $fullfilename;
        }
        return $fullfilename;
    }
}
